package de.wittekind.bundesjugendspiele.client.management.ui.view;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.swing.JFileChooser;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;

import de.wittekind.bundesjugendspiele.client.management.conf.Constants;
import de.wittekind.bundesjugendspiele.client.management.model.CSVLoader;
import de.wittekind.bundesjugendspiele.client.management.ui.UIController;

public class MainActionListener implements ActionListener, TreeSelectionListener {

	
	UIController ui;
	MainView main;
	
	MainActionListener( UIController ui, MainView main ) {
		this.ui = ui;
		this.main = main;

	}
	@Override
	public void actionPerformed(ActionEvent ae) {
		if (ae.getSource() instanceof Component) {
			String src = ((Component) ae.getSource()).getName();
			
			if ( src.equals("save") || src.equals("riegenSave") || src.equals("schuelerSave") ) {
				while (!ui.save())
					;
			}

			if (src.equals("newRiege")) {
				while (!ui.newRiege())
					;
			}

			if (src.equals("newSchueler")) {
				while (!ui.newSchueler())
					;
				System.out.println("event: " + ae.getActionCommand());

			}
			
			if (src.equals("delete")) {
				System.out.println("deleting");
				while (!ui.delete())
					;
			}
			
			if(src.equals("import")) {
				JFileChooser fc = new JFileChooser();
		        int action = fc.showOpenDialog(null);
		        File file = null;
		        if ( action == JFileChooser.APPROVE_OPTION )
                	file = fc.getSelectedFile();
		        imp (file);
			}
			
		}

	}
	
	private boolean imp (File f) {
        try {
			ui.importCSV(f);
		} catch (FileNotFoundException e) {
			return ui.showError("Datei nicht gefunden");
		} catch (IOException e) {
			e.printStackTrace();
			return ui.showError("Server nicht gefunden");
		}
        	return true;
	}
	
	@Override
	public void valueChanged(TreeSelectionEvent e) {

		if (e.getNewLeadSelectionPath() == null)
			return;
		Object o = e.getNewLeadSelectionPath().getLastPathComponent();
		if (o instanceof BujuNode) {
			BujuNode b = (BujuNode) o;

			while (!main.displayNode(b))
				;

		}
	}

}
